package com.company.management.controller;

import com.company.management.config.CustomConfig;
import com.company.management.dto.UserDto;
import com.company.management.service.VersionService;
import com.company.management.utils.FileUtil;
import com.company.management.utils.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ConfigurableObjectInputStream;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;


@Api(tags = "版本管理",value = "版本 VersionController")
@RestController
@RequestMapping("api/version")
@Slf4j
public class VersionController {

    @Resource
    private VersionService versionService;
    @Resource
    private CustomConfig config;
    @Autowired
    private CustomConfig customConfig;

    @ApiOperation("获取版本信息")
    @PostMapping("/version")
    public JsonData getVersion() {
        return JsonData.buildSuccess(versionService.getVersion());
    }
    @ApiOperation("获取APK下载链接")
    @PostMapping("/get-apk-link")
    public JsonData getApkLink() {

        List<Path> pathList = null;
        try{
            pathList =  FileUtil.findApikFiles(config.getApks_folder());
        } catch (IOException e) {
            return JsonData.buildError("获取APK文件失败");
        }
        if (pathList.isEmpty()) {
            return JsonData.buildError("获取APK文件失败");
        }
        String fileName = pathList.get(0).toAbsolutePath().getFileName().toString();
        String apkUrl = config.getBaseurl()+"/api/version/download-apk/" + fileName; // APK文件的HTTP路径
        return JsonData.buildSuccess(apkUrl);
    }

    /**
     * 头像读取
     *
     * @param fileName
     * @param response
     */
    @ApiOperation("下载APK文件")
    @GetMapping("/download-apk/{fileName}")
    public void downloadApk(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {

        ServletOutputStream outputStream;
        log.info("下载APK文件：{}", fileName);
        if(fileName != null){
            String apkPath = config.getApks_folder()+ fileName;
            File apkFile = new File(apkPath);
            log.info("图像路径：{}", apkPath);
            // 设置响应头
            response.setContentType("application/vnd.android.package-archive"); // APK文件的内容类型
            response.setHeader("Content-Disposition", "attachment; filename=\"" + apkFile.getName() + "\"");
            response.setContentLengthLong(apkFile.length());
            try {

                byte[] bytes = cn.hutool.core.io.FileUtil.readBytes(apkPath);
                outputStream = response.getOutputStream();
                outputStream.write(bytes);
            } catch (cn.hutool.core.io.IORuntimeException ior) {response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件下载失败");
            } catch (IOException e){
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件下载失败");
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
